package org.app
package dao

import models.BorrowRecordModel

import scala.collection.mutable.ListBuffer
import scala.io.Source

class BorrowRecordDAO {
  // 读出借阅记录
  def loadBorrowRecords(): ListBuffer[BorrowRecordModel] = {
    val borrowRecords = ListBuffer[BorrowRecordModel]()
    val lines = Source.fromFile("borrow_records.txt")
    for(line <- lines.getLines()){
      val Array(userName,bookID,bookName,borrowDate,returnDate) = line.split(",")
      borrowRecords += BorrowRecordModel(userName,bookID.toInt,bookName,borrowDate,Some(returnDate))
    }
    borrowRecords
  }

  // 写入借阅记录
  def saveBorrowRecords(records: ListBuffer[BorrowRecordModel]): Unit = {
    val writer = new java.io.PrintWriter("borrow_records.txt")
    for(record <- records){
      writer.println(record.userName+","+record.bookID+","+record.bookName+","+record.borrowDate+","+record.returnDate.getOrElse(""))
    }
    writer.close()
  }
}
